import "./indes.css"
import { Modal, Button, Checkbox, Form, Input, message } from "antd"
import { useState, useRef } from "react"
import * as api from "@/api/product"
import Uploader from "./Upload"

const Dialog = (props) => {
    //console.log(props);    //从category里传来的，这里接收
    //状态提升，把visible放到父组件category中，这里接收
    let { visible, handlegetCategory } = props

    //上传之后的图片地址
    let [categoryImgurl, setCategoryImgurl] = useState("")

    //获取form的实例
    let categoryForm = useRef(null)
    //获取表单实例
    // let form = Form.useFormInstance()
    // console.log(form);

    const onFinish = (values) => {
        // console.log('Success:', values);
        if (!categoryImgurl) {
            //如果没用上传图片
            message.error('请上传类目图片')   //这是antd里的组件
        } else {
            //发起请求
            api.addCategory(values.categoryName, values.categoryImgurl)
                .then(res => {
                    console.log(res.data);
                    if (res.data.state) {
                        message.success('添加成功')
                        //更新列表,父组件传递下来的
                        handlegetCategory()
                    }
                })
        }
    };

    const onFinishFailed = (errorInfo) => {
        //console.log('Failed:', errorInfo);
        message.error('请上传类目名称')
    };

    //上传图片之后，可以获取服务器返回的图片地址，通过次方法进行设置
    let handleSetCategoryImgurl = (imgUrl) => {
        setCategoryImgurl(imgUrl)
        console.log(imgUrl);   //得到了图片地址
    }

    return (
        <Modal visible={visible} cancelText='取消' okText='确定' onOk={() => {
            props.onOk(categoryForm)
        }} onCancel={() => {
            props.onCancel()
        }}>
            <Form
                ref={categoryForm}
                name="category"
                labelCol={{
                    span: 8,
                }}
                wrapperCol={{
                    span: 16,
                }}
                initialValues={{
                    remember: true,
                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Form.Item
                    label="类目图片"
                    name="categoryPic"
                >
                    <Uploader onUpload={handleSetCategoryImgurl} />
                </Form.Item>
                <Form.Item
                    label="类目名称"
                    name="categoryName"
                    rules={[
                        {
                            required: true,
                            message: '输入类目的名称',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    )
}

export default Dialog